package be.kuleuven.cs.mop.gui.components;


import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.KeyEvent;

import javax.swing.JLabel;
import javax.swing.JTextField;



public class DurationInput extends Component {
	private static final long serialVersionUID = 1L;
	
	private static final JLabel LABEL = new Label("Duration:");
	
	private final NumericTextField input = new NumericTextField();
	
	
	public DurationInput() {
		super();
		setToolTipText("Duration (in minutes)");
		
		final GridBagConstraints gbc = getGBC();
		gbc.insets	= new Insets(0, 5, 0, 5);
		
		gbc.gridx	= 0;
		gbc.gridy	= 0;
		add(LABEL, gbc);
		
		input.setToolTipText("Enter duration (in minutes)");
		gbc.gridx	= 1;
		add(input, gbc);
	}
	
	
	
	public long read() { return (Long.parseLong(input.getText()) * 60000); }
	
	public void set(final long duration) {
		input.setText(Long.toString(duration / 60000));
	}
	
	
	
	
	
	
	
	
	
	
	
	
	@SuppressWarnings("serial")
	protected static class NumericTextField extends JTextField {
		
		private String backup = "0";
		
		
		protected NumericTextField() {
			super("0");
			setPreferredSize(new Dimension(75, 25));
		}
		
		
		
		@Override
		protected final void processComponentKeyEvent(final KeyEvent event) {
			super.processComponentKeyEvent(event);
			try {
				setText(backup = Long.toString(Long.parseLong(getText())));
			} catch (final NumberFormatException e) {
				setText(backup);
			}
		}
		
	}
	
}